window.playerB = new (class PlayerControl {
  // A 选手   B 选手
  constructor(type) {
    this.type = type;
    this.moveEv = new CustomEvent("keydown");
    this.fireEv = new CustomEvent("keydown");
    this.firetimestamp = (new Date()).valueOf()
    this.priority = this.DIRECTION.STOP;
    this.lasttime = 0
  }

  land() {

    // 当前的坦克实例
    var cur = undefined
    var enr = undefined
    aMyTankCount.forEach(element => {
      var c = element
      if(c['id'] == 200)
      {
        cur = c
      }
      if(c['id'] == 100)
      {
        enr = c
      }
    });
    const currentTank = cur
    const enemyTank = enr
    if (!currentTank) return;

    var moveDirection = this.DIRECTION.STOP
    var cur = (new Date()).valueOf();
    if (cur-this.lasttime > 200){
      this.lasttime = cur
      var rand = parseInt(Math.random() * (4 - 1 + 1) + 1);
      switch(rand)
      {
        case 1:
          moveDirection = this.DIRECTION.UP
          break;
        case 2:
          moveDirection = this.DIRECTION.DOWN
          break;
        case 3:
          moveDirection = this.DIRECTION.LEFT
          break;
        case 4:
          moveDirection = this.DIRECTION.RIGHT
          break;
      }
    }


    this.fire()
    this.move(moveDirection);
    this.setName();
  }

  leave() {
    this.setName();
    document.onkeyup(this.moveEv);
    document.onkeyup(this.fireEv);
  }
  type;
  // private
  // 方向的别名
  DIRECTION = {
    UP: 0,
    RIGHT: 1,
    DOWN: 2,
    LEFT: 3,
    STOP: 4,
  };
  // 开火事件
  fireEv;
  // 移动事件
  moveEv;


  // 设置队伍
  setName() {
    document.getElementById(
        `Player${this.type === "A" ? 1 : 2}barName`
    ).value = "test1"
    document.getElementById(
        `Player${this.type === "A" ? 1 : 2}Name`
    ).textContent = "test1"
  }
  // 控制移动   举例子：  向左移动： this.move(this.DIRECTION.LEFT)
  move(direction) {
    if (typeof direction === undefined) return;
    this.moveEv.keyCode = this.helpDirectionKeyCode(direction);
    document.onkeydown(this.moveEv);
  }
  // 开火
  fire() {
    this.fireEv.keyCode = this.type === "A" ? 32 : 8;
    document.onkeydown(this.fireEv);
  }

  // 根据玩家返回正确的方向keyCode
  helpDirectionKeyCode(direction) {
    switch (direction) {
      case this.DIRECTION.UP:
        return this.type === "A" ? 87 : 38;
      case this.DIRECTION.DOWN:
        return this.type === "A" ? 83 : 40;
      case this.DIRECTION.LEFT:
        return this.type === "A" ? 65 : 37;
      case this.DIRECTION.RIGHT:
        return this.type === "A" ? 68 : 39;
    }
  }
})("B");